package com.example.demo.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.demo.common.*;
import com.example.demo.entity.Notice;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
//import com.github.pagehelper.PageHelper;
//import com.github.pagehelper.PageInfo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Positive;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@CrossOrigin
@Controller
@RequestMapping("/users")
@Transactional//事务
public class UserController {
    @Resource
    private UserService userService;
    @Autowired
    HttpServletRequest request;
    @Autowired
    private JwtUtils jwtUtils;
    /**
     * 查询某个用户接口
     */
    @GetMapping("/{identity_id}")
    @ResponseBody
    //@GetMapping("selectOne")
    public ResultModel selectOne(@PathVariable(value = "identity_id") @Positive(message = "{identity_id}") String identity_id) {
        User user=userService.queryById(identity_id);
        if(user==null){
            return new ResultModel(200,"用户不存在");
        }
        ResultModel resultmodel=new ResultModel();
        resultmodel.setCode(200);
        resultmodel.setData(user);
        return ResultModelTool.handleResultModel(resultmodel);
    }
    /**
     * 获取用户信息接口
     * @return
     *{
     *     "code": 200,
     *     "date": "2020-03-22 21:39:02",
     *     "data": {
     *         "role": 9,
     *         "name": "admin",
     *         "active": 1
     *     }
     * }
     */
    @PostMapping(value = "/information")
    @ResponseBody
    public ResultModel profile(HttpServletRequest request) {
    String authorization = request.getHeader("Authorization");
    if(authorization==null) {
        return new ResultModel(200,"token过期或者权限不足");
}
    String token=authorization;
    //比较并获取claims
    Claims claims = JwtUtils.parseJwt(token);
    String userId = claims.getId();
    User user = userService.queryById(userId);
    Map<String,Object> map = new HashMap<>();
    map.put("role",user.getRole());
    map.put("active",user.getActive());
    map.put("name",user.getName());
    ResultModel resultModel = new ResultModel();
    resultModel.setCode(200);
    resultModel.setData(map);
    return ResultModelTool.handleResultModel(resultModel);
    }
    /**
     * 用户新增
     * @param
     * @return
     */

    @PostMapping("")
    @ResponseBody

    public ResultModel insert(@RequestBody User user){

        String token = request.getHeader("Authorization");
        Claims claims = JwtUtils.parseJwt(token);
        String userId = claims.getId();
        User user1=userService.getUser(userId);
        if(user1==null){
            return new ResultModel(200,"token过期或者权限不足");
        }
        ResultModel resultmodel=new ResultModel();
        resultmodel.setCode(200);
        userService.insertUser(user);
        resultmodel.setData("添加成功");
        return ResultModelTool.handleResultModel(resultmodel);
    }



    //    @PostMapping("")
//    @ResponseBody
//    public ResultModel AddUser(HttpServletRequest request){
//        String name = request.getHeader("name");
//        String identityId = request.getHeader("identityId");
//        String token = request.getHeader("Authorization");
//        Claims claims = JwtUtils.parseJwt(token);
//        String userId = claims.getId();
//        User user=userService.getUser(userId);
//        int role=user.getRole();
//        if(role>=7){
//            User user2=new User();
//            user2.setName(name);
//            user2.setIdentity_id(identityId);
//            user2.setPwd(identityId);
//            userService.addUser(user2);
//            JSONObject jsonObject  = new JSONObject(16, true);
//            JSON.toJSONStringZ(jsonObject, SerializeConfig.getGlobalInstance(), SerializerFeature.QuoteFieldNames);
//            jsonObject.put("id",userService.getUser(identityId).getId());
//            jsonObject.put("identityId",user2.getIdentity_id());
//            ResultModel resultModel = new ResultModel();
//            resultModel.setData(jsonObject);
//            resultModel.setCode(200);
//           return ResultModelTool.handleResultModel(resultModel);
//        }
//        return new ResultModel(403);
//
//    }
    //用户列表
    @GetMapping("")
    @ResponseBody
    public ResultModel GetAllUser() {
        String token = request.getHeader("Authorization");
        Claims claims = JwtUtils.parseJwt(token);
        String userId = claims.getId();
        User user=userService.getUser(userId);

        if(user==null){

            return new ResultModel(200,"token过期或者权限不足");
        }
        List<JSONObject> userList = userService.userlist();
        ResultModel resultModel = new ResultModel();
        resultModel.setData(userList);
        return ResultModelTool.handleResultModel(resultModel);
    }
//    //用户权限提升
//    @PatchMapping ("")
//    @ResponseBody
//    public ResultModel AuthUser(@RequestBody User authUser) {
//        String token = request.getHeader("Authorization");
//        Claims claims = JwtUtils.parseJwt(token);
//        String userId = claims.getId();
//        User user=userService.getUser(userId);
//        int roles=user.getRole();
//        if(roles>=7){
//            int newId = authUser.getId();
//            int newRole = authUser.getRole();
//            userService.authUser(newId, newRole);
//            authUser=userService.getUserById(newId);
//            JSONObject jsonObject  = new JSONObject(16,true);
//            JSON.toJSONStringZ(jsonObject, SerializeConfig.getGlobalInstance(), SerializerFeature.QuoteFieldNames);
//            jsonObject.put("id",authUser.getId());
//            jsonObject.put("name",authUser.getName());
//            jsonObject.put("role",authUser.getRole());
//            ResultModel resultModel = new ResultModel();
//            resultModel.setData(jsonObject);
//            return ResultModelTool.handleResultModel(resultModel);
//        }
//        return new ResultModel(105);
//    }

//    //用户信息修改
//    @PutMapping ("")
//    @ResponseBody
//    public ResultModel UpdateUser(@RequestBody User user){
//        String token = request.getHeader("Authorization");
//        Claims claims = JwtUtils.parseJwt(token);
//        String userId = claims.getId();
//        User user1=userService.getUser(userId);
//        if(user1==null){
//            return new ResultModel(103);
//        }
//        int id=user.getId();
//        int role=user1.getRole();
//        User pastUser=userService.getUserById(id);
//        if(role>=9&&user.getActive()!=null){
//            pastUser.setActive(user.getActive());
//            if(role>=7){
//                if(user.getName()!=null)pastUser.setName(user.getName());
//                if(user.getPwd()!=null) pastUser.setPwd(user.getPwd());
//                if(user.getIdentity_id()!=null)pastUser.setIdentity_id(user.getIdentity_id());
//            }
//        }
//        userService.updateUser(pastUser);
//        ResultModel resultModel = new ResultModel();
//        resultModel.setCode(200);
//        return ResultModelTool.handleResultModel(resultModel);
//    }

    /**
     * 用户修改
     * @param user
     * @return
     */
    @PutMapping ("")
    @ResponseBody
    public ResultModel updateid( @RequestBody User user){

        String token = request.getHeader("Authorization");
        Claims claims = JwtUtils.parseJwt(token);
        String userId = claims.getId();
        User user1=userService.getUser(userId);
        if(user1==null){
            return new ResultModel(200,"token过期或者权限不足");
        }
        ResultModel resultModel=new ResultModel();
        resultModel.setCode(200);
        userService.updateUser(user);
        resultModel.setData("修改成功");
        return ResultModelTool.handleResultModel(resultModel);
    }


    /**
     * 用户删除
     * @param id
     * @return删除时为2 没删除时为1
     */

    @DeleteMapping("/{id}")
    @ResponseBody
    public ResultModel deleteid(@PathVariable(value = "id") @Positive(message = "{id}") int id){

        String token = request.getHeader("Authorization");
        Claims claims = JwtUtils.parseJwt(token);
        String userId = claims.getId();
        User user1=userService.getUser(userId);
        if(user1==null){
            return new ResultModel(200,"token过期或者权限不足");
        }
        userService.deleteid(id);
        ResultModel resultModel=new ResultModel();
        resultModel.setCode(200);
        resultModel.setData("删除成功");
        return ResultModelTool.handleResultModel(resultModel);

    }



//    @GetMapping("/index")
//    @ResponseBody
//    public ResultModel index(@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum,
//                             @RequestParam(defaultValue = "1",value = "pageSize") Integer pageSize){
//        PageHelper.startPage(pageNum,pageSize);
//        List<User> list = userService.findUserList();
//        PageInfo<User> pageInfo = new PageInfo<User>(list);
//        ResultModel resultModel=new ResultModel();
//        resultModel.setData(pageInfo);
//        resultModel.setCode(200);
//        return ResultModelTool.handleResultModel(resultModel);
//    }
}



